package cn.rokka.rbac.web.controller;


import cn.rokka.rbac.anno.RequiredPermission;
import cn.rokka.rbac.qo.JsonResult;
import cn.rokka.rbac.domain.Permission;
import cn.rokka.rbac.qo.QueryObject;
import cn.rokka.rbac.service.IPermissionService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;
import java.util.*;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @RequiredPermission(name = "权限查询", expression = "permission:list")
    public String list(Model model, QueryObject qo) {
        PageInfo<Permission> pageInfo = permissionService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "permission/list";
    }


    @RequestMapping("/delete")
    @RequiredPermission(name = "权限删除", expression = "permission:delete")
    public String delete(Long id) {
        permissionService.delete(id);
        return "redirect:/permission/list";
    }

    @RequestMapping("/input")
    @RequiredPermission(name = "权限编辑", expression = "permission:saveOrUpdate")
    public String input(Long id, Model model) {
        Permission permission = permissionService.getById(id);
        if (permission != null) {
            model.addAttribute("permission", permission);
        }
        return "permission/input";
    }

    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name = "权限编辑", expression = "permission:saveOrUpdate")
    public String saveOrUpdate(Permission dept) {
        if (dept.getId() != null) {
            permissionService.update(dept);
        } else {
            permissionService.save(dept);
        }
        return "redirect:/permission/list";
    }

    @Autowired
    private ApplicationContext ctx;

    @RequestMapping("/load")
    @ResponseBody
    public JsonResult load() {
        /*思路--> :加载权限--->存permission对象到数据库中
         *从上下文(容器)获取所有的controller对象
         * 遍历所有控制器对象
         *拿到字节码对象，通过反射，获取控制器对象的所有方法
         *遍历所有方法，获取带有权限注解的方法，用一变量接收
         *判断对象是否为空..再调用service方法存到数据库中(批量)
         * */
        try {
            List<Permission> existPermissions = permissionService.listAll();
            LinkedHashSet<Object> permissions = new LinkedHashSet<>();
            Map<String, Object> beans = ctx.getBeansWithAnnotation(Controller.class);
            Collection<Object> controllers = beans.values();
            for (Object controller : controllers) {
                Method[] methods = controller.getClass().getDeclaredMethods();
                for (Method method : methods) {
                    RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
                    if (annotation != null) {
                        Permission permission = new Permission();
                        permission.setName(annotation.name());
                        permission.setExpression(annotation.expression());
                        if (!existPermissions.contains(permission)) {
                            permissions.add(permission);
                        }
                    }
                }
            }
            if (permissions.size() > 0) {
                permissionService.batchSave(permissions);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "权限加载失败");
        }
        return new JsonResult(true, "权限加载成功");
    }
}
